#!/usr/bin/env python
# encoding: utf-8
'''
@author: Excelsiorly
@license: (C) Copyright 2021, All Rights Reserved.
@contact: excelsiorly@qq.com
@file: 0035.py
@time: 2021/11/19 14:02
@desc: https://leetcode-cn.com/problems/ba-zi-fu-chuan-zhuan-huan-cheng-zheng-shu-lcof/submissions/
'''


class Solution(object):
    def strToInt(self, str):
        """
        :type str: str
        :rtype: int
        """
        # 去掉空格
        str = str.strip()

        if not str: return 0

        res, i, sign = 0, 1, 1  # 结果, 遍历指针初始化, 符号
        if str[0] == '-':
            sign = -1
        elif not str[0] == '+':
            i = 0  # 若没有一个加号在前方,则从头开始遍历

        # 界限
        int_max, int_min, bndry = 2 ** 31 - 1, -2 ** 31, 2 ** 31 // 10

        for c in str[i:]:
            if not '0' <= c <= '9': break
            if res > bndry or res == bndry and c > '7': return int_max if sign == 1 else int_min
            res = res * 10 + ord(c) - ord('0')

        return sign * res

if __name__ == '__main__':
    res = Solution().strToInt("   -42")
    print(res)